import http from '@/utils/request'
import { setTokenInfo } from '@/utils/storage'
import store, { AppDispatch, RootState } from '..'
import { editPhotoAPI, editProfileAPI } from '@/api/user';
import { ProfileInfo, UserAction } from '../reducers/user';
/**
 * 发送短信验证码
 * @param mobile 手机号
 * @returns
 */
export const sendCodes = (mobile: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/sms/codes/${mobile}`)
    console.log(res)
  }
}
/**
 * 用户认证（登录注册）
 * @param {object} { mobile, code }
 * @returns
 */
 export const Authorizations = ({ mobile, code }: { mobile: string; code: string }) => {
    return async (dispatch: AppDispatch) => {
      const res = await http.post(`/v1_0/authorizations`, { mobile, code })
      console.log(`用户认证（登录注册）`, res)
      dispatch({ type: 'user/saveAuth', payload: res.data })
      setTokenInfo(res.data)
    }
  }
  /**
 * 获取用户自己信息
 * @returns
 */
export const getUserInfo = () => {
    return async (dispatch: AppDispatch) => {
      const res = await http.get(`/v1_0/user`)
      console.log( res)
      dispatch({ type: 'user/saveUser', payload: res.data })
    }
  }
  /**
 * 获取用户个人资料
 * @returns
 */
export const getUserProfile = () => {
    return async (dispatch: AppDispatch) => {
      const res = await http.get(`/v1_0/user/profile`)
      console.log(`/v1_0/user/profile`, res)
      dispatch({ type: 'user/saveProfile', payload: res.data });
    }
  }

  export const editUserPhoto  = (formData: FormData) => {
    return async (dispatch: AppDispatch, getState: () => RootState) => {
      const res = await editPhotoAPI(formData);
      console.log(55, res)
      console.log('state  ----->  ', getState());
      dispatch({
        type: 'user/saveProfile',
        payload: {
          ...getState().user.profile,
          // 3. 覆盖旧的state
          // 4. 关闭弹框
          ...res.data,
        },
      });
    }
  };

  export const editUserProfile = (data: Partial<ProfileInfo>) => {
    return async (dispatch: AppDispatch, getState: () => RootState) => {
    const res = await editProfileAPI(data);
    console.log(73,res);  
      dispatch({
        type: 'user/saveProfile',
        payload: {
          ...getState().user.profile,
          ...data,
        },
      });
    };
  };

  /**
 * 清空用户认证信息
 * @param data Profile 其中一个
 * @returns (dispatch: AppDispatch) => Promise<void>
 */
export const clearAuth = (): UserAction => {
  return { type: 'user/clearAuth' }
}




/**
 * 关注用户和取消关注用户
 * @param target 目标用户（被取消关注的用户id）
 * @returns (dispatch: AppDispatch) => Promise<void>
 */
 export const changeUserFollowings = (target: string) => {
  return async (dispatch: AppDispatch) => {
    const { detail } = store.getState().article
    if (detail.is_followed === false) {
      // 情况1：关注
      await http.post(`/v1_0/user/followings`, { target })
      dispatch({ type: 'article/changeDetail', payload: { is_followed: !detail.is_followed } })
    } else {
      // 情况2：取消关注
      await http.delete(`/v1_0/user/followings/${target}`)
      dispatch({ type: 'article/changeDetail', payload: { is_followed: !detail.is_followed } })
    }
  }
}